#include <pthread.h>
#include <string.h>
#include <X11/Xlib.h>
#include "dwmstatus_types.h"
#include "config.h"
#include "draw_statusbar.h"

pthread_mutex_t draw_exclusive = PTHREAD_MUTEX_INITIALIZER;

void get_status_string(char *buffer, size_t max_size) {

  String item_buffer;
  size_t index;

  memset(buffer, 0, max_size);
  GetDataFunction funcs[] = DATA_FUNCTIONS;

  for (index = 0; funcs[index]; ++index) {
    funcs[index](item_buffer, sizeof(item_buffer));
    if (index)
      safe_strcat(buffer, ITEM_SEPARATOR, max_size);

    safe_strcat(buffer, item_buffer, max_size);

  }
    
}

void xinterface_setstatus(char *str) {
  Display *dpy = NULL;
  dpy = XOpenDisplay(NULL);
  XStoreName(dpy, DefaultRootWindow(dpy), str);
  XSync(dpy, False);
  XCloseDisplay(dpy);
}

void redraw_status() {
  String draw_buffer;

  pthread_mutex_lock(&draw_exclusive);

  get_status_string(draw_buffer, sizeof(draw_buffer));
  xinterface_setstatus(draw_buffer);
  
  pthread_mutex_unlock(&draw_exclusive);
  
} 
